<template>
  <div class="app-container">
    <el-form :inline="true" @submit.native.prevent>
      <el-form-item label="角色名称">
        <el-input v-model="listQuery.name" placeholder="请输入角色名称,回车搜索" style="width: 300px; text-align: right;" @keyup.enter.native="handleResetPage">
          <el-button slot="append" icon="el-icon-search" @click="handleResetPage" />
        </el-input>
      </el-form-item>
      <el-button type="primary" @click="handleAddRole()">新增</el-button>
    </el-form>
    <el-row>
      <el-col :span="24">
        <el-table
          v-loading="listLoading"
          :data="tableList"
          border
          fitedit
          stripe
        >
          <el-table-column label="序号" type="index" align="center" width="60" />
          <el-table-column label="角色名称" prop="name" />
          <el-table-column label="角色编码" prop="code" />
          <el-table-column label="创建时间" prop="time" />
          <el-table-column width="470px" label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="primary" @click="handleAuthorize(scope.row)">菜单授权</el-button>
              <el-button size="small" type="primary" @click="handleLinkUser(scope.row)">关联用户</el-button>
              <el-button v-if="scope.row.roleType !== 0" size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!listLoading">
          <el-pagination :current-page.sync="listQuery.pageVO.pageIndex" :page-sizes="[20,30,50,80]" :page-size="listQuery.pageVO.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="count" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-col>
    </el-row>
    <!-- 弹窗 -->
    <el-dialog
      :title="dialogFormStatus"
      :visible.sync="dialogFormVisible"
      width="30%"
      destroy-on-close
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="80px" @submit.native.prevent>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" :disabled="type === 'info'" @input="handleInput" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" :disabled="type === 'edit'" />
        </el-form-item>
        <el-form-item v-if="type === 'add'" label="状态">
          <el-radio-group v-model="form.status" :disabled="type === 'info'">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancelDialog()">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('form')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="授权页面"
      :visible.sync="dialogAuthorizedVisible"
      destroy-on-close
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="30%"
      class="auth-dialog"
      @close="handleSqDialogClose()"
    >
      <div style="margin-bottom: 10px;">注意：所有层级菜单需要手动勾选,一级菜单勾选才会显示菜单</div>
      <el-form ref="formAuthorize" label-width="100px" @submit.native.prevent>
        <el-tree
          ref="sqMenuTree"
          :props="treeProps"
          :data="menu_tree_data"
          highlight-current
          accordion
          default-expand-all
          :expand-on-click-node="false"
          show-checkbox
          node-key="id"
          check-strictly
          :default-checked-keys="infoMenuUuids"
        />
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="CancelAuthuorize()">取 消</el-button>
        <el-button type="primary" @click="submitAuthuorize()">确 定</el-button>
      </span>
    </el-dialog>
    <UserSelectTable
      :user-select-dialog-show="dialogUsersVisible"
      :user-selected="userSelected"
      @cancel="handleCancelLinkUser"
      @confirm="handleSubmitLinkUser"
    />
  </div>
</template>

<script>
import { pinyin } from 'pinyin-pro'
import UserSelectTable from '@/components/UserSelectTable'

export default {
  components: { UserSelectTable },
  data() {
    return {
      menu_tree_data: [],
      // 查询已经拥有权限菜单的id
      infoMenuUuids: [],
      // 当前选中的所有权限菜单的id
      purviewUuids: [],
      // 选中的所有权限菜单的data
      purviewData: [],
      // 当前点击授权的角色id
      roleUuid: '',
      // 当前点击授权的角色code
      roleCode: '',
      listLoading: false,
      listQuery: {
        pageVO: {
          pageIndex: 1,
          pageSize: 20
        },
        status: undefined,
        name: ''
      },
      count: 0,
      tableList: [],
      type: '',
      dialogFormStatus: '',
      dialogFormVisible: false,
      form: { // 新增和编辑数据存放
        id: undefined,
        code: '',
        name: '',
        status: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入角色编码', trigger: 'blur' }
        ]
      },
      dialogUsersVisible: false, // 显示关联人员的对话框
      setRoleUserData: { // 角色关联用户的存储对象
        roleCode: null,
        users: []
      },
      userSelected: [],
      dialogAuthorizedVisible: false,
      treeProps: {
        label: 'name',
        disabled: (data, node) => {
          return this.roleCode === 'admin' && node.checked
        }
      }
    }
  },
  created() {
    this.search()
  },
  methods: {
    search() {
      this.tableList = [{ code: 'cd_cd', name: '管理员', time: '2022-08-31' }]
    },
    // 点击新增
    handleAddRole() {
      this.type = 'add'
      this.dialogFormStatus = '新增'
      this.dialogFormVisible = true
    },
    // 新增--》名称输入框事件
    handleInput() {
      if (this.type === 'edit') return
      var regCheckChinese = new RegExp('[\u4E00-\u9FA5]+') // 判断是否是中文
      var regEnglish = new RegExp('[A-Za-z]+') // 判断是否是英文
      var regCheckNumber = new RegExp('[0-9]+') // 判断是否是数字
      if (regCheckChinese.test(this.form.name)) {
        var pingyingList = pinyin(this.form.name.trim(), { toneType: 'none', type: 'array' })
        var firstName = pingyingList.shift()
        var _pingyingList = pingyingList.map(item => item.slice(0, 1))
        var code = _pingyingList.length === 0 ? firstName : `${firstName}_${_pingyingList.join('')}`
        this.form.code = code
      } else if (regCheckNumber.test(this.form.name) && !regEnglish.test(this.form.name)) {
        this.form.name = ''
      } else {
        this.form.code = this.form.name
      }
    },
    // 点击编辑菜单
    handleEdit(row) {
      this.form = {
        id: row.id,
        code: row.code,
        name: row.name,
        status: row.status
      }
      this.dialogFormStatus = '编辑'
      this.type = 'edit'
      this.dialogFormVisible = true
    },
    // 授权菜单
    handleAuthorize(row) {
      this.dialogAuthorizedVisible = true
      this.roleUuid = row.id
      this.roleCode = row.code
      // 查询用户的权限
      // getModuleByRoleUuid({
      //   roleCode: row.code
      // }).then(res => {
      //   // this.infoMenuUuids = res.data.uuid
      //   res.data.forEach(item => {
      //     this.infoMenuUuids.push(item.code)
      //   })
      //   this.initMenuTree()
      // })
    },
    // 确认关联人员
    handleSubmitLinkUser(userNos) {
      // setRoleUser({
      //   roleCode: this.setRoleUserData.roleCode,
      //   users: userNos.map(r => { return ({ userName: r.userName, userNo: r.userNo }) })
      // }).then(res => {
      //   if (res.success) {
      //     this.$message.success(userNos.length > 0 ? '已成功关联用户' : '已取消该角色所有用户')
      //     this.handleCancelLinkUser()
      //   }
      // })
    },
    // 取消关联人员对话框的显示
    handleCancelLinkUser() {
      this.dialogUsersVisible = false
      this.setRoleUserData = {
        roleCode: null,
        users: []
      }
    },
    CancelAuthuorize() {
      this.clearPurview()
    },
    // 清空权限的所有id数据
    clearPurview() {
      this.purviewUuids = []
      this.purviewData = []
      this.roleUuid = ''
      this.infoMenuUuids = []
      this.dialogAuthorizedVisible = false
    },
    // 授权弹出层关闭事件
    handleSqDialogClose() {
      this.purviewUuids = []
      this.purviewData = []
      this.roleUuid = ''
      this.infoMenuUuids = []
    },
    // 点击了关联用户
    handleLinkUser(row) {
      this.setRoleUserData.roleCode = row.code
      // getRoleUser({ roleCode: row.code }).then(res => {
      //   // console.log('关联用户: ', res)
      //   if (res.success) {
      //     this.userSelected = res.data
      //     this.setRoleUserData.users = res.data.map(r => { return ({ userName: r.userName, userNo: r.userNo }) })
      this.dialogUsersVisible = true
      //   }
      // })
    },
    // 删除角色 （over）
    handleDelete(row) { // 单个删除
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDelete([row.code])
      }).catch(() => {})
    },
    // 执行删除操作
    doDelete(ids) {
      // deleteRoles(ids).then(res => {
      //   if (res.success) {
      this.$message({ message: '删除成功', type: 'info' })
      //     this.search()
      //   } else this.$message.error(res.message)
      // })
    },
    // 点击确定新增/编辑
    handleConfirm(formRef) {
      this.$refs[formRef].validate(v => {
        // if (v) {
        //   if (this.type === 'edit') { // 编辑
        //     const editData = {
        //       name: this.form.name,
        //       code: this.form.code
        //     }
        //     editRole(editData).then(res => {
        //       this.$message({
        //         message: '编辑成功',
        //         type: 'success'
        //       })
        //       this.search()
        //       this.handleCancelDialog()
        //     })
        //     // 新增
        //   } else if (this.type === 'add') {
        //     addRole(this.form).then(res => {
        //       if (res.success) {
        //         this.$message({
        //           message: '新增成功',
        //           type: 'success'
        //         })
        //         this.search()
        //         this.handleCancelDialog()
        //       } else {
        //         this.$message.error(res.message)
        //       }
        //     })
        //   } else {
        this.handleCancelDialog()
        //   }
        // }
      })
    },
    // 对话框的取消显示
    handleCancelDialog() {
      this.dialogFormVisible = false
      this.form = {
        code: '',
        name: '',
        status: 1
      }
    },
    handleSizeChange(val) { // 切换每页显示个数
      this.listQuery.pageVO.pageSize = val
      this.listQuery.pageVO.pageIndex = 1
      this.search()
    },
    handleCurrentChange(val) { // 切换页码
      this.listQuery.pageVO.pageIndex = val
      this.search()
    },
    // 切换搜索条件时，页码重置
    handleResetPage() {
      this.listQuery.pageVO.pageIndex = 1
      this.search()
    }
  }
}
</script>
<style lang="scss" scoped>

</style>

